#!usr/bin/python
# coding=utf-8

import subprocess
import tempfile  # 临时文件不在系统表中，关闭后自动删除
import traceback
import time
import urllib2
import tarfile
from components.logger import logger


class localsystem(object):

    def commandActuator(self, cmdstring, shell=True, executable='/bin/sh'):
        """
        param: cmdstring-(执行的指令字符串)， shell-(是否是shell指令), executable-(指令所在的目录)
        """
        if executable == '/bin/bash':
            executable = '/bin/bash'
        try:
            logger.info("commandActuator exec command:" + cmdstring)
            # 创建临时文件 subprocess.PIPE大小限制导致挂起
            out_temp = tempfile.SpooledTemporaryFile(bufsize=100 * 1000)
            # 获取临时文件的fileno
            fileno = out_temp.fileno()
            p = subprocess.Popen(cmdstring, shell=shell, stdout=fileno,
                                 stderr=subprocess.STDOUT, executable=executable)
            p.wait()
            # logger.info("during 2")
            # output = []
            # logger.info("during 3")
            # while True:
            #     buff = p.stdout.readline()
            #     output.append(buff)
            #     if buff == '' and p.poll() != None:
            #         break

            out_temp.seek(0)
            output = out_temp.readlines()
            logger.info("commandActuator exec result:" + cmdstring + " |-| " + str(output))
            return output
        except Exception as e:
            logger.error(traceback.format_exc())
        finally:
            if out_temp:
                out_temp.close()

    def get_connected_devices(self):
        """
        获取当前连接到电脑的设备信息
        """
        # count = 0
        # while True:
        cmdout = self.commandActuator("adb devices")
        index = cmdout.index('List of devices attached\n')
        cmdout = [el for el in cmdout if el not in ['', '\n']][index + 1:]
        logger.info("获取当前连接到电脑的设备信息, 连接的设备有:" + str(cmdout))
        dictofdevice = {}
        if len(cmdout) >= 1:
            for line in cmdout:
                sn, status = line.strip('\n').split('\t')
                dictofdevice[sn] = status
            return dictofdevice
        else:
            # count += 1
            # if count > 3:
            logger.info("获取当前连接到电脑的设备信息, adb devices 无法获取到设备")
            return dictofdevice
            # break
            # time.sleep(5)

    def get_connected_devices_in_fastboot_mode(self):
        cmdout = self.commandActuator("fastboot devices")
        cmdout = [el for el in cmdout if el not in ['', '\n']]
        logger.info("获取当前连接到电脑的设备信息, fastboot mode 连接的设备有:" + str(cmdout))
        sn_list = []
        if len(cmdout) >= 1:
            for line in cmdout:
                sn, f_tag = line.strip('\n').split('\t')
                sn_list.append(sn)
            return sn_list
        else:
            logger.info("获取当前连接到电脑的设备信息, 没有在fastboot mode下的设备")
            return sn_list

    def downloadRomAndTarOpen(self, urlstr, private_logger):
        """
        镜像文件下载
        """
        filename = urlstr.split('/')[-1]
        private_logger.info("镜像文件下载 local filename is :" + str(filename))
        uresource = urllib2.urlopen(urlstr)
        fileobjectoflocal = open(filename, 'wb')
        meta = uresource.info()
        filesize = int(meta.getheaders('Content-Length')[0])
        private_logger.info("Downloading: %s Bytes: %s" % (filename, filesize))
        filesizedownload = 0
        blocksize = 819200
        while True:
            buffer = uresource.read(blocksize)
            if not buffer:
                break
            filesizedownload += len(buffer)
            fileobjectoflocal.write(buffer)
            status = r"%10d  [%3.2f%%]" % (
                filesizedownload, filesizedownload * 100. / filesize)
            status = status + chr(8) * (len(status) + 1)
        private_logger.info("下载状态: %s, %s" % (str(status), str(filename)))
        fileobjectoflocal.close()
        dirname = filename.strip('.tgz')
        tarfile.open('./' + filename).extractall('./' + dirname)
        targetdirectory = './' + dirname + '/'
        # private_logger.info("解压目录在: %s" % str(targetdirectory))
        countof_ = filename.count('_')
        for i, v in enumerate(filename):
            if v == '_':
                countof_ -= 1
                if countof_ == 0:
                    targetdirectory += filename[:i]
        # private_logger.info("getrom: %s" % str(targetdirectory))
        return targetdirectory
